// pages/pay/paidOrder/paidOrder.js
const handler=require("../../../utils/function.js")
var config = require("../../../config.js");    
var api = require("../../../api.js"),
    app = getApp();
Page({
    /**
     * 页面的初始数据
     */
    data: {
        img: handler.userImg,
        order: null,
        driver: wx.getStorageSync("serverDriver"),
        reduce: null,
        total: null,
        checkOrder: true,
        checkCoupon: true,
        wechatOrZhifubao: true,
        order_no: '',
      couponList: [],
      choose_coupon:{
        is_open:false,
        message:{}
      },
      actions: [],        //调用配置文件支付设置
      cancelText: '取消',
      show: false,
      cancelWithMask: true,
      clickpay: true,
      wxpays:'',
      order_nos:'',
      pay_prices:'',
      coponids:'' 

    },
    // checkOrderHandler 查看详情事件
    checkOrderHandler: function() {
        this.setData({
            checkOrder: !this.data.checkOrder
        });
    },
    // checkCouponHandler 查看优惠券事件
    checkCouponHandler: function() {
        this.setData({
            checkCoupon: !this.data.checkCoupon
        });
    },
    // callPhoneHandler 打电话事件
    callPhoneHandler: function(e) {
        console.log(e.currentTarget.dataset.phone)
        wx.makePhoneCall({
          phoneNumber: e.currentTarget.dataset.phone
        })
    },
    //
    bindCasPickerChange: function() {},
    // choosePayWayHandler 支付方式事件
    choosePayWayHandler: function() {
        this.setData({
            wechatOrZhifubao: !this.data.wechatOrZhifubao
        });
    },


  openActionsheet() {
    this.setData({
      'show': true
    });
  },
  // 关闭选择器
  closeActionSheet() {
    this.setData({
      'show': false
    });
  },
  // 根据选择进行调用事件
  clickAction({ detail }) {
    const { index } = detail;
    this.setData({
      [`actions[${index}].loading`]: true,
      actionType: index,
      clickpay: true
    });
    switch (index) {
      case 0: // 0 微信支付
        this.wechatPay();
        break;
      case 1: // 1 余额支付
        this.balancePay();
        break;
    }
    setTimeout(() => {
      this.setData({
        [`show`]: false,
        [`actions[${index}].loading`]: false
      });
    }, 100);
  },
// 微信支付
  wechatPay:function(){
    let that = this;
    app.request({
      url: api.order.prepay,
      method: 'post',
      data: {
        coponid: that.data.coponids,
        order_no: that.data.order_nos,
        pay: that.data.wxpays,
        pay_price: that.data.pay_prices,
        pay_type:1
      },
      success: function (rs) {
        if (rs.code == 1) { 
          wx.requestPayment({
            timeStamp: rs.data.timeStamp,
            nonceStr: rs.data.nonceStr,
            package: rs.data.package,
            signType: rs.data.signType,
            paySign: rs.data.paySign,
            success: function (res) {
              console.log('支付回调结果', res)
              wx.showToast({
                title: '支付成功',
                icon: "success"
              });
              wx.redirectTo({
                url: "/pages/userOrder/allOrder/allOrder"
              });
            },
            fail: function (res) {
              console.log('支付回调结果1', res, pay_price)
              //that.setData({ pay_price: pay_price })

              wx.showToast({
                title: '支付失败',
                icon: 'none',
                mask: true
              })
            },
            complete: function (res) {
              console.log('支付回调结果2', res, pay_price)
              // that.setData({ pay_price: pay_price })
            }
          })
        }
        
      }
    })
  },
  //余额支付
  balancePay: function (){
    let that = this;
    app.request({
      url: api.order.prepay,
      method: 'post',
      data: {
        coponid: that.data.coponids,
        order_no: that.data.order_nos,
        pay: that.data.wxpays,
        pay_price: that.data.pay_prices,
        pay_type: 2
      },
      success: function (rs) {
        if(rs.code==1){
          wx.showToast({
            title: '余额支付成功',
            icon: "success",
            duration: 1000
          },
            wx.redirectTo({
              url: "/pages/userOrder/allOrder/allOrder"
            })
          );
          // wx.redirectTo({
          //   url: "/pages/userOrder/allOrder/allOrder"
          // });
        } else if (rs.code == 0){
          wx.showModal({
            content: '余额不足，是否进行充值',
            success(res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: "/pages/driver/top-up/top-up"
                });
              } else if (res.cancel) {
                // console.log('用户点击取消')
              }
            }
          })
        }
      }
    })
  },
    // payHandler 支付事件
    payHandler: function(e) {
        // console.log('支付方式选择', e)
      let that = this;
      var wxpay = e.currentTarget.dataset.wxpay;
      var order_no = e.currentTarget.dataset.order_no;
      var pay_price=this.data.pay_price;
      var coponid = this.data.choose_coupon.message.id;
      that.setData({
        wxpays: wxpay,
        order_nos: order_no,
        pay_prices: pay_price,
        coponids: coponid,
      })
        // console.log(coponid,'支付现金 coponid')
      that.openActionsheet()
        // wx.showModal({
        //     title: '确认支付',
        //     content: "实付现在支付",
        //     success: function(res) {
        //         if (res.confirm) {
        //             const that = this;
        //             app.request({
        //                 url: api.order.prepay,
        //                 method: 'post',
        //                 data: {
        //                     coponid: coponid,
        //                     order_no: order_no,
        //                     pay: wxpay,
        //                     pay_price: pay_price,
        //                 },
        //                 success: function(rs) {
        //                     if (rs.code == 1) {}
        //                     wx.requestPayment({
        //                         'timeStamp': rs.data.timeStamp,
        //                         'nonceStr': rs.data.nonceStr,
        //                         'package': rs.data.package,
        //                         'signType': rs.data.signType,
        //                         'paySign': rs.data.paySign,
        //                         'success': function(res) {
        //                             console.log('支付回调结果', res)
        //                             wx.showToast({
        //                                 title: '支付成功',
        //                                 icon: "success"
        //                             });
        //                           wx.redirectTo({
        //                               url: "/pages/userOrder/allOrder/allOrder"
        //                             });
        //                         },
        //                         'fail': function(res) {
        //                           console.log('支付回调结果1', res, pay_price)
        //                             //that.setData({ pay_price: pay_price })
        //                             wx.showToast({
        //                                 title: '支付失败',
        //                                 icon: "none"
        //                             });
        //                         },
        //                         'complete': function(res) {
        //                           console.log('支付回调结果2', res, pay_price)
        //                           // that.setData({ pay_price: pay_price })
        //                         }
        //                     })
        //                 }
        //             })
        //         }
        //     },
        //     fail: function() {
        //       //that.setData({pay_price:pay_price})
        //         wx.showToast({
        //             title: '支付失败',
        //             icon: "none"
        //         })
        //     }
        // })
      //that.setData({ pay_price: pay_price })
    },
  open_coupon:function(){
    const { choose_coupon}=this.data;
    choose_coupon.is_open=true;
    this.setData({ choose_coupon})
  },
    // 选择优惠券
  getCoupon:function(e){
    var id=e.detail.value;
    if(id!=0){
      const { choose_coupon, couponList, pay_price, order } = this.data;
      choose_coupon.message = couponList[id];
      var paid = parseFloat(order.actual_price) - parseFloat(choose_coupon.message.price);
      console.log(paid)
      this.setData({ choose_coupon, pay_price: paid.toFixed(2)})
    }
  },
  //关闭优惠券
  closeCouponHandler:function(){
    const { choose_coupon, couponList, pay_price, order } = this.data;
    choose_coupon.is_open = false;
    choose_coupon.message = {};
    this.setData({ choose_coupon, pay_price: order.actual_price })
  },
  //选择优惠券
  getCouponHandler:function(){
    const { choose_coupon } = this.data;
    choose_coupon.is_open = false;
    this.setData({ choose_coupon })
  },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setPayWay();
        this.setData({
            order_no: options.order_no
        })
      // 获取优惠券
      if (options.uid) {
        app.shareCouponsMessage(options.uid)
      }
    },
    setPayWay () {
      let that = this;
      var actions = config.actions;
      
      app.request({
        url: api.user.payWay,
        method: 'post',
        success: function (res) {
          console.log(actions[1])
          if (res.data.open_weixin == 0) {
            actions = [actions[1]]
          }
          that.setData({
            actions
          })
        }
      })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {},
    /**
     * 生命周期函数--监听页面显示
     */
  onShow: function() {
      var that = this;
      console.log('api')
      console.log(api.order.order_cost)
      app.request({
          url: api.order.order_cost,
          method: 'post',
          data: {
              order_no: that.data.order_no,
          },
          success: function(rs) {
              if (rs.code == 1) {
                if (rs.data.is_pay == 1) {
                  wx.redirectTo({
                      url: '../paidDetail/paidDetail?order_no=' + that.data.order_no,
                  })
                }
                that.setData({
                  order: rs.data,
                  pay_price: rs.data.actual_price,
                  work_phone: rs.data.work_phone,
                  signature: rs.data.signature
                })
                var couponList = []
                if (rs.data.CouponList.length==0){
                  // couponList = [{ name: "暂无优惠券"}];
                  couponList = [];
                }else{
                  couponList = [{ name: "优惠券名称", price: '价格' }];
                  for (var i = 0; i < rs.data.CouponList.length; i++) {
                    couponList.push(rs.data.CouponList[i]);
                  }
                }
                that.setData({ couponList})
                // console.log(rs.data.CouponList, couponList,'rs.data.CouponList')
              }
          }
      })
      // 初始化数据
    this.setData({
      choose_coupon: {
        is_open: false,
        message: {}
      },})
  },
  priceRule:function(e){
    console.log(e,'2222222222');
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },
  // 用户分享
  onShareAppMessage: function () {
    let title = app.shareAppMessage().title;
    let imageUrl = app.shareAppMessage().imageUrl;
    let desc = app.shareAppMessage().desc;
    let path = app.shareAppMessage().path;
    // console.log(app.shareAppMessage())
    return {
      title: title,
      imageUrl: imageUrl,
      desc: desc,
      path: path,
    }
  },
})